<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-text">需求申请单管理</div>
          <div class="title-sub">DEMAND REQUEST MANAGEMENT</div>
        </div>
        <div class="header-glow"></div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 搜索面板 -->
      <div class="search-panel">
        <div class="panel-header">
          <div class="panel-title">
            <span class="title-icon">🔍</span>
            筛选
          </div>
          <div class="panel-subtitle">根据关键词快速定位需求</div>
        </div>

        <a-form
            :model="searchForm"
            layout="inline"
            class="search-form"
        >
          <a-form-item class="search-item" label="部门">
            <a-input class="search-input"
                     v-model:value="searchForm.dpmNameCn"
                     placeholder="请输入部门关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
          <a-form-item class="search-item" label="角色">
            <a-input class="search-input"
                     v-model:value="searchForm.roleName"
                     placeholder="请输入角色关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
          <a-form-item class="search-item" label="业务">
            <a-input class="search-input"
                     v-model:value="searchForm.businessName"
                     placeholder="请输入业务关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
          <a-form-item class="search-item" label="痛点">
            <a-input class="search-input"
                     v-model:value="searchForm.fmDesc"
                     placeholder="请输入痛点关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
          <a-form-item class="search-item" label="控制要求">
            <a-input class="search-input"
                     v-model:value="searchForm.cpSpec"
                     placeholder="请输入控制要求关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
          <a-form-item class="search-item" label="反应计划">
            <a-input class="search-input"
                     v-model:value="searchForm.reactionPlanCn"
                     placeholder="请输入反应计划关键词"
                     allow-clear
                     @pressEnter="handleSearch"
            >
            </a-input>
          </a-form-item>
        </a-form>
        <div class="button-panel">
          <a-button type="primary" class="search-btn" @click="handleSearch">
            <SearchOutlined />
            查询
          </a-button>
          <a-button class="reset-btn" @click="handleReset">
            <RedoOutlined />
            重置
          </a-button>
        </div>
      </div>

      <!-- 数据列表面板 -->
      <div class="data-panel">
        <div class="panel-header">
          <div class="panel-title">
            <span class="title-icon">📊</span>
            需求列表
            <a-button class="add-btn" @click="handleAdd">
              <PlusOutlined />
              新增
            </a-button>
            <a-button
                class="preview-btn"
                @click="handlePreview"
                :disabled="isPreviewDisabled"
                :loading="previewLoading"
            >
              <EyeOutlined />
              {{ previewLoading ? '加载中...' : '预览' }}
            </a-button>
          </div>
          <div class="data-stats">
            共 <span class="highlight">{{ pagination.total }}</span> 条记录
            <span v-if="selectedRow" class="selected-info"> | {{ selectedInfo }}</span>
          </div>
        </div>
        <a-table
            :data-source="tableData"
            :columns="columns"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            :custom-row="customRow"
            bordered
            size="middle"
            class="tech-table"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'createDate'">
              <span class="date-cell">{{ record.createDate }}</span>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <Modal
        v-model:open="modalVisible"
        :title="modalTitle"
        :footer="null"
        :mask-closable="false"
        :width="'80%'"
        @esc="handleModalClose"
        class="requirement-modal"
    >
      <RequirementDetails
          :mode="'add'"
          :loading="modalLoading"
          @confirm="handleModalConfirm"
          @esc="handleModalClose"
      />
    </Modal>
    <Modal
        v-model:open="previewModalVisible"
        title="需求申请单预览"
        :footer="null"
        :mask-closable="false"
        :width="'90%'"
        @esc="handlePreviewClose"
        class="preview-modal"
    >
      <RequirementDetails
          v-if="previewData"
          :mode="'preview'"
          :preview-data="previewData"
          @esc="handlePreviewClose"
      />
      <div v-else class="loading-container">
        <a-spin size="large" />
        <div class="loading-text">加载中...</div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.app-container {
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  min-height: 100vh;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.header {
  height: calc(100vh / 6);
  background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 50%, #6366f1 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(14, 165, 233, 0.3);
}

.header::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url("/akitorSys.svg");
  background-size: 100% 100%;
  opacity: 0.5;
}

.header-content {
  position: relative;
  z-index: 2;
  text-align: center;
}

.header-title {
  color: white;
}

.title-text {
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 1px;
  margin-bottom: 5px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.title-sub {
  font-size: 14px;
  opacity: 0.9;
  letter-spacing: 2px;
  font-weight: 300;
}

.header-glow {
  position: absolute;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.4) 0%, rgba(59, 130, 246, 0) 70%);
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
}

.main-content {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.search-panel, .data-panel {
  background: rgba(30, 41, 59, 0.7);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  padding: 24px;
  margin-bottom: 24px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
}

.search-panel::before, .data-panel::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, #0ea5e9, transparent);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-title {
  font-size: 18px;
  font-weight: 600;
  color: #f8fafc;
  display: flex;
  align-items: center;
}

.title-icon {
  margin-right: 10px;
  font-size: 20px;
}

.panel-subtitle {
  font-size: 14px;
  color: #94a3b8;
}

.data-stats {
  font-size: 14px;
  color: #94a3b8;
}

.highlight {
  color: #0ea5e9;
  font-weight: 600;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 0;
}

.search-form .search-item {
  margin-bottom: 0;
  margin-right: 20px;
  flex: 30%;
  min-width: 200px;
}
.search-form .search-item::v-deep(.ant-form-item-control) {
   flex: 1;
   min-width: 80px;
 }

.search-form .search-item :deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #e2e8f0;
}

.search-form .search-input {
  border-radius: 8px;
  border: 1px solid #334155;
  background: rgba(15, 23, 42, 0.7);
  color: #f1f5f9;
  transition: all 0.3s ease;
}

.search-form .search-input:hover {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.2);
}

.search-form .search-input:focus {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.3);
}

.search-form .search-item .search-input::v-deep(.ant-input) {
  background: transparent;
  color: #f1f5f9;
}

.search-form .search-input::v-deep(.ant-input)::placeholder {
  color: #64748b;
}

.button-panel {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  width: 100%;
  justify-content: flex-end;
}

.preview-btn {
  border: 1px solid #475569;
  background: rgba(15, 23, 42, 0.7);
  color: #94a3b8;
  margin-left: 12px;
}

.preview-btn:hover {
  border-color: #10b981;
  color: #10b981;
  background: rgba(16, 185, 129, 0.1);
  transform: translateY(-1px);
}

.preview-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.search-btn, .reset-btn, .add-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  height: 40px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  gap: 6px;
  border: none;
  position: relative;
  overflow: hidden;
}

.search-btn {
  background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(14, 165, 233, 0.4);
}

.search-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.search-btn:hover::before {
  left: 100%;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(14, 165, 233, 0.6);
}

.reset-btn {
  border: 1px solid #475569;
  background: rgba(15, 23, 42, 0.7);
  color: #94a3b8;
}

.reset-btn:hover {
  border-color: #0ea5e9;
  color: #0ea5e9;
  background: rgba(14, 165, 233, 0.1);
  transform: translateY(-1px);
}

.add-btn {
  border: 1px solid #475569;
  background: rgba(15, 23, 42, 0.7);
  color: #94a3b8;
  margin-left: 20px;
}

.add-btn:hover {
  border-color: #0ea5e9;
  color: #0ea5e9;
  background: rgba(14, 165, 233, 0.1);
  transform: translateY(-1px);
}

.tech-table::v-deep(.ant-table) {
  background: transparent;
  color: #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
}

.tech-table :deep(.ant-table-thead > tr > th) {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  color: #f8fafc;
  border-bottom: 1px solid #475569;
  font-weight: 600;
  padding: 12px 16px;
}

.tech-table :deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid #334155;
  padding: 12px 16px;
  background: rgba(30, 41, 59, 0.5);
  transition: all 0.2s ease;
}

.tech-table :deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(14, 165, 233, 0.1);
}

.tech-table::v-deep(.ant-table-pagination) {
  margin: 16px 0 0 0;
  color: #94a3b8;
}

.tech-table::v-deep(.ant-pagination-item) {
  background: rgba(30, 41, 59, 0.7);
  border: 1px solid #475569;
}

.tech-table :deep(.ant-pagination-item a) {
  color: #94a3b8;
}

.tech-table::v-deep(.ant-pagination-item-active) {
  background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
  border-color: #0ea5e9;
}

.tech-table :deep(.ant-pagination-item-active a) {
  color: white;
}

.tech-table::v-deep(.ant-pagination-prev .ant-pagination-item-link, .ant-pagination-next .ant-pagination-item-link) {
  background: rgba(30, 41, 59, 0.7);
  border: 1px solid #475569;
  color: #94a3b8;
}

.date-cell {
  color: #0ea5e9;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}
.requirement-modal{
  display: flex;
}
::v-deep(.requirement-modal .ant-modal-content) {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

::v-deep(.requirement-modal .ant-modal-header) {
  background: transparent;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 16px 24px;
}

::v-deep(.requirement-modal .ant-modal-title) {
  color: #f8fafc;
  font-size: 16px;
  font-weight: 600;
}

::v-deep(.requirement-modal .ant-modal-close) {
  color: #94a3b8;
}

::v-deep(.requirement-modal .ant-modal-close:hover) {
  color: #0ea5e9;
}

::v-deep(.requirement-modal .ant-modal-body) {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 添加选中行样式 */
.tech-table :deep(.ant-table-tbody > tr.selected-row > td) {
  background: linear-gradient(135deg, rgba(14, 165, 233, 0.3) 0%, rgba(59, 130, 246, 0.2) 100%) !important;
  border-color: #0ea5e9;
  position: relative;
}

.tech-table :deep(.ant-table-tbody > tr.selected-row > td::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
}

.tech-table :deep(.ant-table-tbody > tr.selected-row:hover > td) {
  background: linear-gradient(135deg, rgba(14, 165, 233, 0.4) 0%, rgba(59, 130, 246, 0.3) 100%) !important;
}

.selected-info {
  color: #0ea5e9;
  margin-left: 8px;
  font-weight: 500;
}

/* 添加行鼠标悬停效果 */
.tech-table :deep(.ant-table-tbody > tr) {
  cursor: pointer;
  transition: all 0.2s ease;
}

/* 预览弹窗样式 */
.preview-modal {
  display: flex;
}

::v-deep(.preview-modal .ant-modal-content) {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  max-height: 90vh;
}

::v-deep(.preview-modal .ant-modal-header) {
  background: transparent;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 16px 24px;
}

::v-deep(.preview-modal .ant-modal-title) {
  color: #f8fafc;
  font-size: 16px;
  font-weight: 600;
}

::v-deep(.preview-modal .ant-modal-body) {
  padding: 0;
  max-height: calc(90vh - 55px);
  overflow-y: auto;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #94a3b8;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
}

</style>

<script setup lang="ts">
import {computed, nextTick, onMounted, reactive, ref} from "vue";
import {Form, Input, Button, message,Table,Modal,Spin} from 'ant-design-vue';
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined ,
  EyeOutlined,
} from '@ant-design/icons-vue';
import api from "@/utils/api";
import RequirementDetails from './requirementDetails.vue';

const AForm = Form;
const AFormItem = Form.Item;
const AInput = Input;
const AButton = Button;
const ATable = Table;
const ASpin = Spin;

// 表格数据
const tableData = ref<any[]>([]);
// 加载状态
const loading = ref(false);
// 初始搜索表单数据（用于重置）
const initialSearchForm = {
  dpmNameCn: '',
  roleName: '',
  businessName: '',
  fmDesc: '',
  cpSpec: '',
  reactionPlanCn: '',
};


const previewModalVisible = ref(false);
const previewData = ref<any>(null);
const previewLoading = ref(false);

// 预览处理函数
const handlePreview = async () => {
  if (!selectedRowKey.value) {
    message.warning('请先选择一条记录进行预览');
    return;
  }

  try {
    previewLoading.value = true;
    previewData.value = null; // 先清空数据
    previewModalVisible.value = false; // 先关闭弹窗

    console.log('开始加载预览数据，ID:', selectedRowKey.value);

    // 修正接口URL路径
    const response = await api.get(`/requirement/dtoRequirementDetails/id?id=${selectedRowKey.value}`, {
      timeout: 5000 // 延长超时时间
    });

    console.log('预览接口响应状态:', response.status);
    console.log('预览接口响应数据:', response.data);

    if (response.data && Object.keys(response.data).length > 0) {
      previewData.value = response.data;

      // 使用nextTick确保数据已经设置到组件
      await nextTick();

      // 短暂延迟确保DOM更新完成
      setTimeout(() => {
        previewModalVisible.value = true;
        console.log('预览弹窗已打开，数据已设置');
      }, 50);
    } else {
      console.warn('预览接口返回空数据或无效数据');
      message.warning('未找到相关数据或数据格式不正确');
    }
  } catch (error: any) {
    console.error('预览数据加载失败:', error);

    // 更详细的错误信息
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('错误状态码:', error.response.status);
      console.error('错误响应数据:', error.response.data);

      if (error.response.status === 404) {
        message.error('未找到该需求申请单的详细信息');
      } else if (error.response.status === 500) {
        message.error('服务器内部错误，请稍后重试');
      } else {
        message.error(`请求失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else if (error.request) {
      // 请求发送了但没有收到响应
      console.error('网络错误，未收到响应:', error.request);
      message.error('网络连接异常，请检查网络后重试');
    } else {
      // 其他错误
      console.error('其他错误:', error.message);
      message.error('预览数据加载失败，请重试');
    }
  } finally {
    previewLoading.value = false;
  }
};

// 关闭预览弹窗
const handlePreviewClose = () => {
  previewModalVisible.value = false;
  setTimeout(() => {
    previewData.value = null;
    selectedRowKey.value = null;
    selectedRow.value = null;
  }, 300);
};

const searchForm = reactive({ ...initialSearchForm });

const handleSearch = async () => {
  try {
    loading.value = true;
    selectedRowKey.value = null;
    selectedRow.value = null;

    // 构建查询参数
    const searchParams = {
      dpmNameCn: searchForm.dpmNameCn.trim(),
      roleName: searchForm.roleName.trim(),
      businessName: searchForm.businessName.trim(),
      fmDesc: searchForm.fmDesc.trim(),
      cpSpec: searchForm.cpSpec.trim(),
      reactionPlanCn: searchForm.reactionPlanCn.trim(),
      current: pagination.current,
      pageSize: pagination.pageSize,
    };

    console.log('查询参数:', searchParams);

    const response = await api.get('/requirement/dtoRequirement', {
      params: searchParams,
      timeout: 5000
    });

    let data = [];
    let total = 0;

    // 更健壮的数据提取逻辑
    if (response.data) {
      if (response.data.data && Array.isArray(response.data.data)) {
        // 分页响应格式
        data = response.data.data;
        total = response.data.total || 0;
      } else if (Array.isArray(response.data)) {
        // 直接返回数组格式
        data = response.data;
        total = response.data.length;
      } else if (response.data.records && Array.isArray(response.data.records)) {
        // 另一种分页格式
        data = response.data.records;
        total = response.data.total || 0;
      }
    }

    tableData.value = data;
    pagination.total = total;

    // 检查数据是否包含预览所需的基本字段
    if (data.length > 0) {
      const sampleRecord = data[0];

      // 验证数据是否包含必要的预览字段
      const hasPreviewFields = sampleRecord.id !== undefined &&
          sampleRecord.dpmNameCn !== undefined;

      if (!hasPreviewFields) {
        console.warn('表格数据缺少预览所需的必要字段');
      }
    }

  } catch (error) {
    console.error('查询失败:', error);
    message.error('查询失败，请重试');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 预览按钮状态计算属性
const isPreviewDisabled = computed(() => {
  return !selectedRowKey.value || previewLoading.value;
});

// 选中的行信息显示
const selectedInfo = computed(() => {
  if (selectedRow.value) {
    return `已选中: ${selectedRow.value.dpmNameCn} - ${selectedRow.value.roleName} - ${selectedRow.value.businessName}`;
  }
  return '';
});

// 在handleReset中重置选中状态
const handleReset = () => {
  Object.assign(searchForm, initialSearchForm);
  tableData.value = [];
  selectedRowKey.value = null;
  selectedRow.value = null;
  message.info('已重置搜索条件');
};


const modalVisible = ref(false);
const modalTitle = ref('新增需求申请单');
const modalLoading = ref(false);

const handleAdd = () => {
  modalTitle.value = '新增需求申请单';
  modalVisible.value = true;
};

// 关闭弹窗
const handleModalClose = () => {
  modalVisible.value = false;
};

// 弹窗确认回调
const handleModalConfirm = async (formData: any) => {
  try {
    modalLoading.value = true;

    // 调用新增API
    const response = await api.post('/requirement/add', formData);

    if (response.data && response.data.success) {
      message.success('新增需求申请单成功');
      modalVisible.value = false;
      // 刷新表格数据
      await handleSearch();
    } else {
      message.error(response.data.message || '新增失败');
    }
  } catch (error) {
    console.error('新增失败:', error);
    message.error('新增失败，请重试');
  } finally {
    modalLoading.value = false;
  }
};

const columns = [
  {
    title: '部门',
    dataIndex: 'dpmNameCn',
    key: 'roleName',
    width: 120,
  },
  {
    title: '角色',
    dataIndex: 'roleName',
    key: 'roleName',
    width: 120,
  },
  {
    title: '业务',
    dataIndex: 'businessName',
    key: 'businessName',
    width: 120,
  },
  {
    title: '痛点',
    dataIndex: 'fmDesc',
    key: 'fmDesc',
    width: 150,
  },
  {
    title: '控制要求',
    dataIndex: 'cpSpec',
    key: 'cpSpec',
    width: 150,
  },
  {
    title: '反应计划',
    dataIndex: 'reactionPlanCn',
    key: 'reactionPlanCn',
    width: 150,
  },
  {
    title: '价值主张',
    dataIndex: 'value',
    key: 'value',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'createDate',
    key: 'createDate',
    width: 180,
  },
];

const showTotal = (total: number) => `共 ${total} 条`;
// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: showTotal,
  pageSizeOptions: ['10', '20', '50', '100'],
});

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  handleSearch();
};

// 在组件挂载时自动加载数据
onMounted(() => {
  // handleSearch(); //页面加载不要自动搜索
});

// 添加选中相关变量
const selectedRowKey = ref<string | number | null>(null);
const selectedRow = ref<any>(null);

// 自定义行属性
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const customRow = (record: any) => {
  return {
    style: {
      cursor: 'pointer',
    },
    onClick: () => {
      selectedRowKey.value = record.id;
      selectedRow.value = record;
    },
    class: {
      'selected-row': selectedRowKey.value === record.id
    }
  };
};

</script>